package org.afi.mushroomplayer.components;

import java.util.ArrayList;
import java.util.List;

import org.afi.mushroomplayer.MainActivity.OnEventHandleListener;
import org.afi.mushroomplayer.R;
import org.afi.mushroomplayer.adapter.SongAdapter;
import org.afi.mushroomplayer.model.SongInfo;
import org.afi.mushroomplayer.utils.SongUtils;


import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;

public class AllSongsView extends RelativeLayout implements OnCheckedChangeListener, OnItemClickListener {

    private static final String TAG = "ALL";
	private RadioGroup mRadioGroup;
	private ListView mAllListView;
	private SongAdapter mAdapter;
	private List<SongInfo> mSongList;
	private OnEventHandleListener mEventHandleListener;
	
	public AllSongsView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public void initView(Context context) {
	    mSongList = new ArrayList<SongInfo>();
		mRadioGroup = (RadioGroup) findViewById(R.id.radiogroup);
		mAllListView = (ListView) findViewById(R.id.songlist);
		mAdapter = new SongAdapter(context);
		mAdapter.setListData(mSongList);
		mAllListView.setAdapter(mAdapter);
		mAllListView.setOnItemClickListener(this);
		mRadioGroup.setOnCheckedChangeListener(this);
	}
	
	public ListView getListView() {
	    return mAllListView;
	}
	
	public void setEventHandleListener(OnEventHandleListener listener) {
	    this.mEventHandleListener = listener;
	}
	
	public void setSongList(List<SongInfo> list) {
	    this.mSongList = list;
	    mAdapter.setListData(mSongList);
	    mAdapter.notifyDataSetChanged();
	}

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (mSongList != null) {
            if (checkedId == R.id.by_title) {
                mSongList = SongUtils.sort(mSongList, 1);
            } else if (checkedId == R.id.by_artist) {
                mSongList = SongUtils.sort(mSongList, 2);
            } else if (checkedId == R.id.by_album) {
                mSongList = SongUtils.sort(mSongList, 3);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        mEventHandleListener.handleEvent(OnEventHandleListener.EVENT_TYPE_SLIDE_TO_PLAYING_VIEW, null, mSongList, position);
        SongUtils.getSongInfoFromUrl(getContext(), mSongList.get(position).getUrl());
    }

}
